<template>
  <div v-if="!editing" @mouseenter="onMouseOver" @mouseleave="onMouseOut">
    <div class="question-done-area">
      <div class="title-area">
        <span>{{ number + "." + question.title }}</span>
        <span v-if="question.must" style="color: red">*</span>
      </div>
      <div class="remark">
        <span> {{ question.remark }} </span>
      </div>
      <el-checkbox-group v-model="answer">
        <div v-for="(option, i) in question.options" :key="i">
          <el-checkbox :label="option.title"></el-checkbox>
          <span v-if="option.limit"> 限额:{{ option.limit }} </span>
        </div>
      </el-checkbox-group>
      <transition name="bounce">
        <div class="operation-buttons" v-show="seen">
          <div @click="editQuestion">
            <i class="el-icon-edit"></i>
            <span style="cursor: pointer">编辑</span>
          </div>
          <div @click="deleteQuestion">
            <i class="el-icon-delete"></i>
            <span style="cursor: pointer">删除</span>
          </div>
          <div @click="duplicateQuestion">
            <i class="el-icon-document-copy"></i>
            <span style="cursor: pointer">复制</span>
          </div>
        </div>
      </transition>
    </div>
  </div>
  <div v-else>
    <el-card class="single">
      <el-form ref="form" :model="form" label-width="80px" :rules="rules">
        <el-form-item label="题目" prop="title">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark"></el-input>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="form.must">必填</el-checkbox>
          <span style="margin-left: 20px" v-if="signup"
            >选项内容右方选择选项限选人数 若不限选则填0</span
          >
        </el-form-item>
        <el-form-item
          v-for="(choice, i) in form.options"
          :label="'选项' + (i + 1)"
          :key="i"
          :prop="'options.' + i + '.title'"
          :rules="{
            required: true,
            message: '选项不能为空',
            trigger: 'blur',
          }"
        >
          <el-input
            v-if="signup"
            style="width: 40%; margin-right: 20px"
            v-model="choice.title"
            placeholder="右边选择题目限选人数 若无限额请输入0"
          ></el-input>
          <el-input
            v-else
            style="width: 40%; margin-right: 20px"
            v-model="choice.title"
          ></el-input>
          <el-input-number
            v-if="signup"
            style="margin-right: 20px"
            v-model="choice.limit"
            @change="handleChange"
            :min="0"
            :max="9999"
          ></el-input-number
          ><el-button @click.prevent="removeDomain(choice)">删除</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('form')">确定</el-button>
          <el-button @click="addDomain">新增选项</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
  import axios from "axios";
  export default {
    props: {
      question: Object,
      number: Number,
      getQuestionnaire: Function,
      questionnaire_id: Number,
      addQuestion: Function,
      signup: Boolean,
    },
    data() {
      return {
        answer: [],
        form: null,
        rules: {
          title: [{ required: true, message: "请输入题目名称", trigger: "blur" }],
        },
        timer: null,
        editing: false,
        seen: false,
      };
    },
    methods: {
      onMouseOver() {
        this.seen = true;
      },
      onMouseOut() {
        this.seen = false;
      },
      duplicateQuestion() {
        var formData = JSON.parse(JSON.stringify(this.question));
        formData["id"] = null;
        for (var i = 0; i < formData.options.length; i++) {
          formData.options[i]["id"] = null;
        }
        this.addQuestion(formData);
      },
      async deleteQuestion() {
        const form = {
          questionnaire_id: this.questionnaire_id,
          username: localStorage.getItem("username"),
        };
        var breakfunc = false
        await axios.post("isallowed/", form).then((response) => {
          // console.log('yessss')
          if (response.data.code == -3) {
            // 发布中不许改
            this.$notify.error({
              title: "错误",
              message: "问卷正处于发布状态，无法编辑",
            });
            this.getQuestionnaire();
            console.log('我摊牌了')
            breakfunc = true
          } else if (response.data.code == -4) {
            // 该问卷已被浏览过 请在副本中编辑
            this.$notify({
              title: "警告",
              message: "该问卷已被浏览，无法编辑，请在已自动复制的副本中进行编辑",
              type: "warning",
            });
            this.getQuestionnaire();
            breakfunc = true
          }
        });
        if(breakfunc) {return}
        const formData = {
          question_id: this.question.id,
        };
        axios.post("delete_question/", formData);
        clearTimeout(this.timer);
        this.timer = setTimeout(() => {
          this.getQuestionnaire();
        }, 200);
      },
      removeDomain(item) {
        if (this.form.options.length <= 2) {
          return;
        }
        var index = this.form.options.indexOf(item);
        if (index !== -1) {
          this.form.options.splice(index, 1);
        }
      },
      addDomain() {
        this.form.options.push({
          title: "",
          option_id: 0,
        });
      },
      cancel() {
        this.editing = false;
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            //   执行提交
            axios.post("questions/", this.form).then((response) => {
              console.log(response.status);
              console.log(response.data);
            });
            clearTimeout(this.timer);
            this.timer = setTimeout(() => {
              this.getQuestionnaire();
              // location.reload()
              this.editing = false;
            }, 200);
          } else {
            console.log("error submit!!");
            console.log(this.form);
            return false;
          }
        });
      },
      async editQuestion() {
        const form = {
          questionnaire_id: this.questionnaire_id,
          username: localStorage.getItem("username"),
        };
        var breakfunc = false
        await axios.post("isallowed/", form).then((response) => {
          // console.log('yessss')
          if (response.data.code == -3) {
            // 发布中不许改
            this.$notify.error({
              title: "错误",
              message: "问卷正处于发布状态，无法编辑",
            });
            this.getQuestionnaire();
            console.log('我摊牌了')
            breakfunc = true
          } else if (response.data.code == -4) {
            // 该问卷已被浏览过 请在副本中编辑
            this.$notify({
              title: "警告",
              message: "该问卷已被浏览，无法编辑，请在已自动复制的副本中进行编辑",
              type: "warning",
            });
            this.getQuestionnaire();
            breakfunc = true
          }
        });
        if(breakfunc) {return}
        this.form = JSON.parse(JSON.stringify(this.question));
        // 一些无聊的赋值操作
        // 实在是不优雅qwq
        this.form["questionnaire_id"] = this.questionnaire_id;
        this.form["question_id"] = this.question.id;
        this.form["username"] = localStorage.getItem("username");
        for (var i = 0; i < this.form.options.length; i++) {
          this.form.options[i]["option_id"] = this.form.options[i].id;
        }
        // 终于结束了
        this.editing = true;
      },
    },
  };
</script>
<style scoped>
.title-area {
  margin: 5px;
  font-size: 14px;
}

.operation-buttons {
  width: 40%;
  margin: 0 auto;
  font-size: 15px;
  display: flex;
  justify-content: space-evenly;
  border: 1px solid;
  border-radius: 20px;
  margin-top: 20px;
}

.el-icon-edit,
.el-icon-delete,
.el-icon-document-copy {
  cursor: pointer;
}
.remark {
  margin-top: 5px;
  margin-bottom: 5px;
  margin-left: 10px;
}
.bounce-enter-active {
  animation: bounce-in 0.3s;
}
.bounce-leave-active {
  animation: bounce-in 0.2s reverse;
}
@keyframes bounce-in {
  0% {
    transform: scale(0);
  }
  50% {
    transform: scale(1.25);
  }
  100% {
    transform: scale(1);
  }
}
</style>